package com.cgy.utils.elasticsearch.single;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.support.replication.ReplicationResponse;
import org.elasticsearch.action.update.UpdateResponse;

/**
 * @author CH
 */
@Slf4j
public class ElasticSearchUpdate {
    /**
     *
     * @param response
     */
    public static boolean response(UpdateResponse response) {
        String indexName = response.getIndex();
        String typeName = response.getType();
        String documentId = response.getId();
        if (response.getResult() == DocWriteResponse.Result.CREATED) {
            log.info("文档新增成功！index: {}, type: {}, id: {}", indexName, typeName, documentId);
            return true;
        } else if (response.getResult() == DocWriteResponse.Result.UPDATED) {
            log.info("文档更新成功！");
            return true;
        } else if (response.getResult() == DocWriteResponse.Result.DELETED) {
            log.error("\"index={},type={},id={}\"的文档已被删除，无法更新！", indexName, typeName, documentId);
            return false;
        } else if (response.getResult() == DocWriteResponse.Result.NOOP) {
            log.error("操作没有被执行！");
            return false;
        }

        ReplicationResponse.ShardInfo shardInfo = response.getShardInfo();
        if (shardInfo.getTotal() != shardInfo.getSuccessful()) {
            log.error("分片副本未全部处理");
        }
        if (shardInfo.getFailed() > 0) {
            for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {
                String reason = failure.reason();
                log.error("未处理原因：{}", reason);
            }
        }
        return false;
    }
}
